package top.went.service;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.went.db.dao.*;
import top.went.exception.NotFoundException;
import top.went.exception.ServiceException;
import top.went.pojo.*;
import top.went.vo.OrderVo;
import top.went.vo.PageEntity;

import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Service
@Transactional(value = "transactionManager", rollbackFor = ServiceException.class)
public class ApprovalService {
    private final ApprovalDao approvalDao;
    @Autowired
    private ApprovalLogsDao approvalLogsDao;
    private final QuoteDao quoteDao;
    private final PurchaseDao purchaseDao;
    private final OrderService orderService;
    private final OrderDao orderDao;

    @Autowired
    public ApprovalService(ApprovalDao approvalDao,  QuoteDao quoteDao, PurchaseDao purchaseDao, OrderService orderService, OrderDao orderDao) {
        this.approvalDao = approvalDao;
        this.quoteDao = quoteDao;
        this.purchaseDao = purchaseDao;
        this.orderService = orderService;
        this.orderDao = orderDao;
    }

    public List<ApprovalEntity> findApprovalById(Integer id,String type){
        return approvalDao.findById(id,type);
    }

    /**
     * 审批
     * @param approvalLogsEntity
     * @param userEntity
     * @param status
     * @throws ServiceException
     */
    public void approval(ApprovalLogsEntity approvalLogsEntity, UserEntity userEntity,int status)
            throws ServiceException {
        ApprovalEntity approvalEntity = approvalDao.loadOne(approvalLogsEntity.getTbApprovalByApprovalId().getApprovalOrderId(),
                     approvalLogsEntity.getTbApprovalByApprovalId().getApprovalType());
        if (approvalEntity!=null&&approvalEntity.getApprovalStatus()==null &&(status != 1))
            throw new ServiceException("不存在审批记录");
        if (approvalEntity == null) {
            approvalEntity = approvalLogsEntity.getTbApprovalByApprovalId();
            approvalEntity.setTbUserByApprovalUserId(userEntity);
            approvalEntity.setApprovalApplyTime(Date.valueOf(LocalDate.now()));
            approvalEntity.setApprovalStatus("1");
        }
        if (approvalEntity.getApprovalStatus().equals("2") && status != 4)
            throw new ServiceException("该审批已经通过，无法修改");
        if (status >1) {
            approvalEntity.setTbUserByApprovalReceiverId(userEntity);
            approvalEntity.setApprovalTime(Date.valueOf(LocalDate.now()));
        }
        approvalEntity.setApprovalStatus(String.valueOf(status));
        approvalLogsEntity.setLogsTime(Timestamp.valueOf(LocalDateTime.now()));
        approvalLogsEntity.setTbUserByUserId(userEntity);
        approvalLogsEntity.setCategory(getCategory(status));
        approvalLogsEntity.setTbApprovalByApprovalId(approvalEntity);
        try {
            approvalLogsDao.save(approvalLogsEntity);
            change(approvalEntity);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("审批错误");
        }
    }

    private String getCategory(int status){
        switch (status){
            case -1:
                return "撤销审批";
            case 1:
                return "申请审批";
            case 2:
                return "同意";
            case 3:
                return "否决";
            case 4:
                return "解锁";
        }
        return "";
    }
    /**
     * 新增审批单
     *
     * @param orderId
     * @param type
     * @return
     * @throws ServiceException
     */
    public boolean addApproval(Long orderId, String type, UserEntity userEntity) throws ServiceException {
        try {
            ApprovalEntity approvalEntity = new ApprovalEntity();
            if (userEntity == null) {
                return false;
            }
            approvalEntity.setTbUserByApprovalUserId(userEntity);
            approvalEntity.setApprovalApplyTime(new Date(System.currentTimeMillis()));
            approvalEntity.setApprovalOrderId(orderId.intValue());
            approvalEntity.setApprovalType(type);
            approvalEntity.setApprovalStatus("未审批");

            approvalDao.save(approvalEntity);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("新增审批单错误");
        }
        return true;
    }


    /**
     * 分页查找所有审批单
     *
     * @param pageNumber
     * @param pageSize
     * @return
     * @throws ServiceException
     */
    public PageEntity<ApprovalEntity> queryAll(Integer pageNumber, Integer pageSize) throws ServiceException {
        try {
            PageRequest pageRequest = new PageRequest(pageNumber, pageSize);
            List<ApprovalEntity> list = approvalDao.findAllApps(pageRequest);
            PageEntity pageEntity = new PageEntity(approvalDao.count(), list);
            return pageEntity;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查找审批记录错误");
        }
    }

    /**
     * 根据申请人分页查找所有审批单
     *
     * @param userId
     * @param pageNumber
     * @param pageSize
     * @return
     * @throws ServiceException
     */
    public PageEntity<ApprovalEntity> queryAllByUser(Long userId, Integer pageNumber, Integer pageSize) throws ServiceException {
        try {
            PageRequest pageRequest = new PageRequest(pageNumber, pageSize);
            List<ApprovalEntity> list = approvalDao.findAllByUser(userId, pageRequest);
            PageEntity pageEntity = new PageEntity(approvalDao.countAllByUser(userId), list);
            return pageEntity;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查找审批记录错误");
        }
    }

    /**
     * 根据分类分页查找所有审批单
     *
     * @param type
     * @param pageNumber
     * @param pageSize
     * @return
     * @throws ServiceException
     */
    public PageEntity<ApprovalEntity> queryAllByType(String type, Integer pageNumber, Integer pageSize) throws ServiceException {
        try {
            PageRequest pageRequest = new PageRequest(pageNumber, pageSize);
            List<ApprovalEntity> list = approvalDao.findAllByApprovalType(type, pageRequest);
            PageEntity pageEntity = new PageEntity(approvalDao.countAllByApprovalType(type), list);
            return pageEntity;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查找审批记录错误");
        }
    }

    /**
     * 根据申请人和类型分页查找所有审批单
     *
     * @param userId
     * @param type
     * @param pageNumber
     * @param pageSize
     * @return
     * @throws ServiceException
     */
    public PageEntity<ApprovalEntity> queryAllByUserAndType(Long userId, String type, Integer pageNumber, Integer pageSize) throws ServiceException {
        try {
            PageRequest pageRequest = new PageRequest(pageNumber, pageSize);
            List<ApprovalEntity> list = approvalDao.findAllByUserAndType(userId, type, pageRequest);
            PageEntity pageEntity = new PageEntity(approvalDao.countAllByUserAndType(userId, type), list);
            return pageEntity;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查找审批记录错误");
        }
    }

    /**
     * 加载审批
     *
     * @param approvalId
     * @return
     * @throws ServiceException
     */
    public ApprovalEntity load(Long approvalId) throws ServiceException {
        try {
            return approvalDao.loadOne(approvalId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("加载错误");
        }
    }

    public List<ApprovalEntity> findAll() throws ServiceException {
        try {
//            List<ApprovalEntity> list = new ArrayList<ApprovalEntity>();
            List<ApprovalEntity> apps = (List<ApprovalEntity>) approvalDao.findAll();
            for (ApprovalEntity app : apps) {
                if (app.getApprovalType().equals("订单")) {
                    OrderEntity order = orderService.load(app.getApprovalOrderId().longValue());
                    app.setApprovalTitle(order.getOrderTitle());
                } else if (app.getApprovalType().equals("采购单")) {
                    PurchaseEntity purchase = purchaseDao.findAllByMagicDeleteAndPurId(0L, app.getApprovalOrderId());
                    if (purchase != null) {
                        app.setApprovalTitle(purchase.getPurTheme());
                    }
                } else if (app.getApprovalType().equals("报价单")) {
                    QuoteEntity quote = quoteDao.findAllByQuoteIdAndIsDelete(app.getApprovalOrderId().longValue(), 0L);
                    if (quote != null) {
                        app.setApprovalTitle(quote.getQuoteTheme());
                    }
                }
            }
            return apps;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查找所有审批单成功");
        }
    }


    private void change(ApprovalEntity app) throws NotFoundException {
        if (app.getApprovalStatus().equals("-1") || app.getApprovalStatus().equals("4"))
            app.setApprovalStatus("0");
        if (app.getApprovalType().equals("订单")) {
            OrderEntity order = orderService.load(app.getApprovalOrderId().longValue());
            System.out.println("订单数据：" + order.toString());
            order.setOrderOk(Integer.parseInt(app.getApprovalStatus()));
            orderDao.save(order);
        } else if (app.getApprovalType().equals("采购单")) {
            PurchaseEntity purchase = purchaseDao.findAllByMagicDeleteAndPurId(0L, app.getApprovalOrderId());
            if (purchase != null) {
                purchase.setPurOk(Integer.valueOf(app.getApprovalStatus()));
                purchaseDao.save(purchase);
            }
        } else if (app.getApprovalType().equals("报价单")) {
            QuoteEntity quote = quoteDao.findAllByQuoteIdAndIsDelete(app.getApprovalOrderId().longValue(), 0L);
            if (quote != null) {
                quote.setApprovalStatus(Long.valueOf(app.getApprovalStatus()));
                quoteDao.save(quote);
            }
        }
    }
}
